<template>
  <!--银行流水-->
  <BasicModal :width="1100" v-bind="$attrs"
    :title="getTitle"
    :canFullscreen="false"
    :centered="true"
    :destroyOnClose="true"
    :bodyStyle="{height:'500px', overflowY:'hidden'}"
    @register="registerModal"
    @ok="handleSubmit"
  >
  <split leftWidth="400" style="margin-top: 4px; overflow: hidden">
    <template #paneL>
      <BasicForm @register="registerForm" :model="model" />
    </template>
    <template #paneR>
      <BasicTable @register="registerTable" :onRowClick="handleClick" :onRowDbClick="handleDblclick" :rowClassName="rowClassName" >
        <template #tableTitle>
          <a-button type="primary" color="success" @click="handleCreate" :disabled="!model.id" preIcon="ant-design:sisternode-outlined" > 分解 </a-button>
          <a-button type="primary" preIcon="ant-design:edit-outlined" @click="handleEdit" :disabled="editDisabled"> 编辑</a-button>
          <a-button type="primary" color="error" preIcon="ant-design:delete-twotone" @click="handleDelete" :disabled="deleDisabled"> 删除 </a-button>
        </template>
        <template #action="{ record }">
          <TableAction :actions="getTableAction(record)" />
        </template>
      </BasicTable>
    </template>
  </split>
  </BasicModal>
  <!-- 分解新增 -->
  <BankDecomposeModel @register="registerBankDecomposeAdd" @success="modalFormOk" :canResize="true"></BankDecomposeModel>
</template>

<script lang="ts" name="BankBusinessModal" setup>
  import {ref, computed, unref, reactive} from 'vue';
  import {BasicModal, useModalInner, useModal} from '/@/components/Modal';
  import {BasicForm, useForm} from '/@/components/Form/index';
  import {BasicTable, TableAction, ActionItem, BasicColumn, useTable} from '/@/components/Table';
  import {bankRunningSave, bankRunningById, bankDecomposeList, deleteBankRunning} from "/@/views/full/bank/types/bank.api";
  import {useMessage} from "/@/hooks/web/useMessage";
  import {useListPage} from '/@/hooks/system/useListPage';
  import {filterObj} from '/@/utils/common/compUtils';
  import {render} from '/@/utils/common/renderUtils';

  import Split from '/@/components/pt/split/Index.vue'
  import moment from 'dayjs'
  import BankDecomposeModel from './BankDecomposeModel.vue';

  //----------定义变量 开始-------------------------------------------------------------
  const $message = useMessage();
  // 声明Emits
  const emit = defineEmits(['success', 'register']);
  // 表单modal
  const model = reactive<any>({})
  const isUpdate = ref(true);

  // 定义查询 - 查询条件
  const editDisabled = ref<boolean>(true);
  const deleDisabled = ref<boolean>(true);
  const queryParam = reactive<any>({});

  //标题
  const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

  //----------定义变量 结束-------------------------------------------------------------


  // --------------左边--表单----------------------------------------
  // 表单检查
  const rules = reactive({
    bankId: [ { required: true, message: '必须选择银行' }, ],
    sflx: [ { required: true, message: '必须选择收付类型' }, ],
    jzsj: [ { required: true, message: '必须选择记账日期' }, ],
    je: [ { required: true, message: '必须输入金额' }, ],
  })

  // 定义表单
  const [registerForm, {resetFields, setFieldsValue, validate}] = useForm({
    schemas: [
      { label: "系统编号", field: "id", component: "Input", show: true, componentProps: { readonly: true } },
      {
        label: "收支账户",
        field: "bankId",
        component: "JDictSelectTag",
        componentProps: {
          dictCode: "chee_bank,djm,id@ddlxBank",
          placeholder: " ",
          stringToNumber: true
        },
        required: true
      },
      {
        label: "收支类型",
        field: "sflx",
        component: "JDictSelectTag",
        componentProps: { dictCode: "sflxType", placeholder: " " },
        required: true
      },
      {
        label: "记账日期",
        field: "jzsj",
        component: "DatePicker",
        defaultValue: moment().format("YYYY-MM-DD"),
        componentProps: { valueFormat: "YYYY-MM-DD" }
      }, //, rules: [{required: true, type: 'string'}],
      {
        label: "金额",
        field: "je",
        component: "InputNumber",
        componentProps: { placeholder: " " },
        rules: [{ required: true, type: "number" }]
      },
      { label: "对方户名", field: "dfhm", component: "Input", componentProps: { placeholder: " " } },
      { label: "对方账户", field: "dfzh", component: "Input", componentProps: { placeholder: " " } },
      { label: "备注", field: "bz", component: "InputTextArea", componentProps: { placeholder: " " } }
    ],
    labelWidth: 100,
    baseColProps: {span: 20},
    showActionButtonGroup: false,
  });

  // 表单初始化
  const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
    setModalProps({confirmLoading: false});
    isUpdate.value = !!data?.isUpdate;
    await resetFields()
    let record = data?.record || {}
    if (isUpdate.value) {
      record = await bankRunningById({id:data?.record?.id});
      await setFieldsValue(record)
      Object.assign(model, record);
      queryParam.parentId = model.id
      searchQuery();
    } else {
      Object.assign(model, {id: ''});
      queryParam.parentId = ""
    }
  });

  // 表单提交事件
  async function handleSubmit() {
    try {
      setModalProps({confirmLoading: true});
      const values = await validate();
      await bankRunningSave(values).then((res) => {
        if (res.success) {
          $message.createMessage.success(res.message);
          //关闭弹窗
          closeModal();
          emit("success")
        } else {
          $message.createMessage.warning(res.message);
        }
      });
    } catch (e) {
      console.log("handleSubmit - 提交校验出错", e);
    } finally {
      setModalProps({confirmLoading: false});
    }
  }
  // --------------左边--表单----------------------------------------

  // --------------右边--列表----------------------------------------
  const statusFmt = ({ text }: { text: any }) => {
    if (text && text !== '合计') {
      const color = text == '0' ? 'green' : text == '1' ? 'red' : 'green';
      const value = text == '0' ? '未审' : text == '1' ? '已审' : '未审';
      return render.renderTag(value, color);
    }
  };
  // 订单列表 - 表头
  const columns: BasicColumn[] = [
    { title: '状态', align: 'center', dataIndex: 'shbj', width: 56, customRender: statusFmt },
    { title: '部门', align: 'center', dataIndex: 'ddlx', width: 70, customRender: ({ text }) => render.renderDict(text, 'ddlxType') },
    { title: '银行账户', align: 'left', dataIndex: 'djm', width: 135 },
    { title: '收入', align: 'right', dataIndex: 'srje', width: 91, className: 'text-red-500' },
    { title: '支出', align: 'right', dataIndex: 'zcje', width: 91, className: 'text-green-500' },
    { title: '备注', align: 'left', dataIndex: 'bz', width: 110 },
    { title: '操作人', align: 'center', dataIndex: 'lrr', width: 60 },
    { title: '操作时间', align: 'center', dataIndex: 'lrsj', width: 85 },
  ];

  // 列表页面公共参数、方法
  const loading = ref<boolean>(false);
  const dataSource = ref<any[]>([]);
  const summaryData = ref<any[]>([]);
  const { prefixCls, tableContext } = useListPage({
    designScope: 'bankDecompose-list',
    tableProps: {
      rowKey: "id",
      size: "small",
      dataSource: dataSource,
      columns: columns,
      showTableSetting: false,
      showIndexColumn: true, //行号
      showActionColumn: false,
      useSearchForm: false,
      resizeHeightOffset: 60,
      minHeight: 300,
      maxHeight: 360,
      pagination: false,
      showSummary: true,
      summaryData: summaryData,
    }
  });

  //注册table数据
  const [registerTable, { reload, setProps, getRawDataSource, redoHeight }] = tableContext;

  async function loadRootData() {
    if (!queryParam.parentId) {
      return false;
    }
    loading.value = true;
    await bankDecomposeList(filterObj(queryParam)).then( res => {
      if (res.success) {
        dataSource.value = res.rows;
        summaryData.value = res.footer;
      } else {
        dataSource.value = [];
        summaryData.value = [];
      }
    }).finally(() => {
      loading.value = false;
    });
    console.info('loadRootData@@@@', summaryData.value)
  }

  //分解组件
  const [registerBankDecomposeAdd, { openModal: openBankDecomposeModal }] = useModal();
  // --------------右边--列表----------------------------------------

  // --------------组件--事件----------------------------------------
  //单击行
  let selectRows = reactive<any>({ id: '', username: '' });
  function handleClick(record) {
    selectRows.id = record.id;
    selectRows.username = record.username;
    if (record.shbj == '1') {
      editDisabled.value = true;
      deleDisabled.value = true;
    } else {
      editDisabled.value = false;
      deleDisabled.value = false;
    }
  }

  //双击行
  function handleDblclick(record) {
    if (record.shbj === '0') {
      handleEdit();
    } else {
    }
  }

  function rowClassName(record, index) {
    return record.id === selectRows.id ? 'row-selected' : '';
  }

  /**
   * 新增
   */
  function handleCreate() {
    openBankDecomposeModal(true, { model, isUpdate: false });
  }

  /**
   * 编辑
   */
  function handleEdit() {
    let record = { id: selectRows.id };
    openBankDecomposeModal(true, { model, record, isUpdate: true });
  }

  /**
   * 删除
   */
  async function handleDelete() {
    await deleteBankRunning({ id: selectRows.id }, modalFormOk);
  }

  /**
   * 解分表单提交成功后刷新列表
   */
  function modalFormOk() {
    searchQuery();
  }

  /**
   * 查询
   */
  function searchQuery() {
    loadRootData();
  }
  // --------------组件--事件----------------------------------------
</script>

<style lang="less" scoped>

</style>
